#include "bufferQue.h"

void bMakeEmpty(bufferQue *Q){
    (*Q).rear = -1;
    (*Q).front = 0;
}

int bIsEmpty(bufferQue Q){
    return (Q.rear < Q.front);
}

int bEnque(bufferQue *Q, uint8_t x){
    int i;  
    //printf("REAR : %d\n", (*Q).rear);
    (*Q).rear = (*Q).rear + 1;
  
    if ((*Q).rear >= MAXBUFFERLENGTH){
        //printf("MAXBUFFERLENGTH");
        if ((*Q).front > 0) {
            //geser
            //printf("geser");
            
            for (i = 0; i <  ((*Q).rear-(*Q).front); ++i){
                (*Q).data[i] = (*Q).data[(*Q).front+i];            
            }
            (*Q).rear = ((*Q).rear-(*Q).front);
            (*Q).front = 0;
            (*Q).data[(*Q).rear] = x;
            return 1;
        } else {
            (*Q).rear = MAXBUFFERLENGTH-1;
            return 0;
        }
    } else {
        (*Q).data[(*Q).rear] = x;
        return 1;
    }
}


int bDeque(bufferQue *Q){
    int retval = -1;
    if ((!bIsEmpty(*Q))&&((*Q).front < MAXBUFFERLENGTH)){
        retval = (*Q).data[(*Q).front];
        (*Q).front++;
    }
    return retval;
}

int bLen(bufferQue Q){
    if (bIsEmpty(Q)){
        return 0;
    } else {
        return (Q.rear - Q.front + 1);
    }
}

#ifdef PC
void printBufferQue(bufferQue Q){
    int i;
    printf("R: %d  F:%d\n:: ", Q.rear, Q.front);
    for (i = Q.front; i <= Q.rear; ++i){
        printf(" %d",Q.data[i]);
    } 
    printf("\n");
}

#endif

